﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Small.Express
{
   public static class OrderByCondictionExtension
    {

       /// <summary>
       /// 动态排序
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="source"></param>
       /// <param name="orderBy">根据值查询</param>
       /// <param name="orderOption"></param>
       /// <returns></returns>
       public static IQueryable<T> DynamicOrderBy<T>(this IQueryable<T> source, string sortField, OrderOptions orderOptions = OrderOptions.Asc) 
       {
           string sortingDir = string.Empty;
           if (orderOptions.ToString().ToUpper().Trim() == "ASC") 
           {
               sortingDir = "OrderBy";

           }
           else if (orderOptions.ToString().ToUpper() == "DESC") 
           {
               sortingDir = "OrderByDescending";
           }
           ParameterExpression param = Expression.Parameter(typeof(T), sortField);
           PropertyInfo pi = typeof(T).GetProperty(sortField);
           Type[] types = new Type[2];
           types[0] = typeof(T);
           types[1] = pi.PropertyType;
           Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortField), param));
           IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);
           return query;
           
         
       }
    }
}
